package io.gitee.caoxiaoyu97.log4j.defender.message.log;

import io.gitee.caoxiaoyu97.log4j.defender.properties.DefenderKeyProperties;

import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.springframework.util.StringUtils;

public class RegexValueDefender extends AbstractLogDefender<Pattern> {
    public RegexValueDefender(DefenderKeyProperties properties) {
        super(properties);
    }


    protected Set<Pattern> transformToMatcher(DefenderKeyProperties properties) {
        Set<String> keys = readKeysFromProperty(properties.getKeys(), properties.getSplitter());
        return (Set<Pattern>) keys.stream().filter(it -> !StringUtils.isEmpty(it))
                .map(key -> Pattern.compile(key)).collect(Collectors.toSet());
    }


    public StringBuilder doDesensitize(StringBuilder inputOrigin) {
        StringBuilder input = inputOrigin;
        String tmpMsg = "";
        for (Pattern pattern : this.toMatchKeys) {
            Matcher matcher = pattern.matcher(input);
            while (matcher.find()) {
                tmpMsg = matcher.group();
                tmpMsg = this.strategy.doMark(tmpMsg);
                input = input.replace(matcher.start(), matcher.end(), tmpMsg);
                matcher = pattern.matcher(input);
            }
        }
        return input;
    }


    protected boolean isQuickMatch(StringBuilder input) {
        return true;
    }
}
